import Vue from 'vue'
import {QWebChannel} from './qwebchannel'
import {Message, Notification} from 'element-ui'

if (process.env.NODE_ENV === 'development') {
  window.qt = {
    webChannelTransport: {
      send() {
        console.log(`
              QWebChannel simulator activated !
              启动QT桌面端后请注销此段代码,并在QT中进行查看!
              QTWEBENGINE_REMOTE_DEBUGGING=9927 启动QT后使用此接口在浏览器中调试
            `)
      }
    }
  }
}

export var callBackDict = {}

export var qtWebChannel = null // 导出qtWebChannel，供其他页面调用
new QWebChannel(qt.webChannelTransport, (channel) => {
  // all published objects are available in channel.objects under
  // the identifier set in their attached WebChannel.id property
  qtWebChannel = channel.objects.bridge
  Vue.prototype.$QtCallBackDict = callBackDict
  Vue.prototype.$QtWebChannel = qtWebChannel
  Vue.prototype.$request = request
  console.log(qtWebChannel)
  ChannelCallBack()
  // 进入回调地狱
})

function request(func, data = null) {
  Vue.prototype.$QtWebChannel.request(
    JSON.stringify({func: func, data: data})
  )
}

// 回调地狱
function ChannelCallBack() {
  console.log('初始化')
  qtWebChannel.connectSignal.connect(connectSignalCallBack)
}

function connectSignalCallBack(jsonString) {
  /*
  res: {
      code: 200/400 400就是后台有问题
      func: string 在mount中载入
      data: Dict 传入到view函数中
  }
  */
  // console.info(callBackDict)
  const res = JSON.parse(jsonString)
  // 根据code码 想要什么信息提示框就自己整合
  console.log(res)
  switch (res.code) {
    case 200:
      const func = res.data.func;
      const data = res.data.data;
      callBackDict[func](data);
      return;
    case 400:
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      });
      return;
    case 201:
      Notification({
        type: 'success',
        title: 'INFO',
        message: res.message || "Success",
        duration: 5 * 1000
      });
      return;
  }
}
